package Socket;




import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;


/**
 * @author 徐梦轲
 * @create 2022-06-25 10:25
 */
public class Server {
    private DatagramSocket socket = null;
    public Server(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }
    public void start() throws IOException {
        while (true) {
            System.out.println("服务器启动");
            //接收请求
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(requestPacket);
            //处理请求
            String request = new String(requestPacket.getData(),0, requestPacket.getLength());
            String response = process(request);
            //发送响应
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),response.getBytes().length,requestPacket.getSocketAddress());
            socket.send(responsePacket);
            //日志打印
            String log = String.format("[ %s : %d ] request: %s response: %s",
                    requestPacket.getAddress(),requestPacket.getPort(),request,response);
            System.out.println(log);

        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        Server server= new Server(9090);
        server.start();
    }
}
